# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-07-15 23:28
# File     : real_time_streaming.py
# Project  : dynamic-portfolio-optimizer
# Desc     : 实时数据流示例
# examples/real_time_streaming.py
"""
实时数据流示例
"""

import asyncio
import sys
from pathlib import Path
import pandas as pd
from datetime import datetime
import time
import threading

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.services.market_data_service import MarketDataService


class RealTimeMonitor:
    """实时市场监控器"""

    def __init__(self, symbols: list, update_interval: int = 60):
        self.symbols = symbols
        self.update_interval = update_interval
        self.market_service = MarketDataService()
        self.running = False
        self.data_history = {}

        # 价格变化阈值
        self.alert_threshold = 0.05  # 5%

    def start_monitoring(self):
        """开始监控"""
        self.running = True
        print(f"🚀 开始监控 {len(self.symbols)} 只股票...")
        print(f"📊 更新间隔: {self.update_interval}秒")
        print(f"⚠️ 价格变化警报阈值: {self.alert_threshold:.1%}")
        print("-" * 60)

        try:
            while self.running:
                self._update_prices()
                time.sleep(self.update_interval)
        except KeyboardInterrupt:
            print("\n⏹️ 监控已停止")
            self.running = False

    def _update_prices(self):
        """更新价格数据"""
        try:
            # 获取实时报价
            quotes = self.market_service.get_real_time_quote(self.symbols)

            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"\n🕒 更新时间: {current_time}")

            for symbol in self.symbols:
                if symbol in quotes and quotes[symbol]:
                    quote = quotes[symbol]

                    # 检查价格变化
                    self._check_price_alerts(symbol, quote)

                    # 显示价格信息
                    self._display_price_info(symbol, quote)

                    # 保存历史数据
                    self._save_to_history(symbol, quote)
                else:
                    print(f"❌ {symbol}: 无法获取数据")

            print("-" * 60)

        except Exception as e:
            print(f"❌ 更新价格时出错: {e}")

    def _check_price_alerts(self, symbol: str, quote: dict):
        """检查价格警报"""
        change_percent = quote.get('change_percent', 0) / 100

        if abs(change_percent) >= self.alert_threshold:
            alert_type = "🚨 大涨" if change_percent > 0 else "🚨 大跌"
            print(f"{alert_type} {symbol}: {change_percent:+.2%}")

    def _display_price_info(self, symbol: str, quote: dict):
        """显示价格信息"""
        price = quote.get('price', 0)
        change = quote.get('change', 0)
        change_percent = quote.get('change_percent', 0)
        volume = quote.get('volume', 0)

        # 选择表情符号
        if change > 0:
            emoji = "📈"
        elif change < 0:
            emoji = "📉"
        else:
            emoji = "➡️"

        print(f"{emoji} {symbol:6s}: ${price:8.2f} "
              f"({change:+6.2f}, {change_percent:+5.1f}%) "
              f"Vol: {volume:,}")

    def _save_to_history(self, symbol: str, quote: dict):
        """保存到历史数据"""
        if symbol not in self.data_history:
            self.data_history[symbol] = []

        # 添加时间戳
        quote_with_time = quote.copy()
        quote_with_time['timestamp'] = datetime.now()

        self.data_history[symbol].append(quote_with_time)

        # 只保留最近100条记录
        if len(self.data_history[symbol]) > 100:
            self.data_history[symbol] = self.data_history[symbol][-100:]

    def get_price_trends(self, symbol: str, window: int = 10) -> dict:
        """获取价格趋势"""
        if symbol not in self.data_history or len(self.data_history[symbol]) < window:
            return {}

        recent_data = self.data_history[symbol][-window:]
        prices = [item['price'] for item in recent_data]

        if len(prices) >= 2:
            price_change = prices[-1] - prices[0]
            price_change_percent = (price_change / prices[0]) * 100

            # 计算简单趋势
            if price_change_percent > 1:
                trend = "上升"
            elif price_change_percent < -1:
                trend = "下降"
            else:
                trend = "横盘"

            return {
                'trend': trend,
                'change': price_change,
                'change_percent': price_change_percent,
                'avg_price': sum(prices) / len(prices)
            }

        return {}

    def stop_monitoring(self):
        """停止监控"""
        self.running = False


class WatchlistManager:
    """观察列表管理器"""

    def __init__(self):
        self.watchlists = {
            'tech_giants': ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'],
            'ev_stocks': ['TSLA', 'NIO', 'XPEV', 'LI', 'RIVN'],
            'semiconductors': ['NVDA', 'AMD', 'INTC', 'TSM', 'QCOM'],
            'finance': ['JPM', 'BAC', 'WFC', 'GS', 'MS'],
            'healthcare': ['JNJ', 'PFE', 'UNH', 'ABBV', 'MRK']
        }

    def get_watchlist(self, name: str) -> list:
        """获取观察列表"""
        return self.watchlists.get(name, [])

    def list_watchlists(self) -> dict:
        """列出所有观察列表"""
        return self.watchlists

    def add_symbol(self, watchlist_name: str, symbol: str):
        """添加股票到观察列表"""
        if watchlist_name in self.watchlists:
            if symbol not in self.watchlists[watchlist_name]:
                self.watchlists[watchlist_name].append(symbol)
                print(f"✅ 已添加 {symbol} 到 {watchlist_name}")
            else:
                print(f"⚠️ {symbol} 已在 {watchlist_name} 中")
        else:
            print(f"❌ 观察列表 {watchlist_name} 不存在")


def main():
    """主函数"""

    print("📊 实时股票监控系统")
    print("=" * 50)

    # 创建观察列表管理器
    watchlist_manager = WatchlistManager()

    # 显示可用的观察列表
    print("📋 可用的观察列表:")
    for name, symbols in watchlist_manager.list_watchlists().items():
        print(f"   {name}: {', '.join(symbols)}")

    # 让用户选择观察列表
    print("\n请选择要监控的观察列表 (默认: tech_giants):")
    chosen_list = input("输入观察列表名称: ").strip() or 'tech_giants'

    symbols = watchlist_manager.get_watchlist(chosen_list)
    if not symbols:
        print(f"❌ 观察列表 '{chosen_list}' 不存在，使用默认列表")
        symbols = watchlist_manager.get_watchlist('tech_giants')

    # 设置更新间隔
    print("\n⏰ 请设置更新间隔 (秒，默认60):")
    try:
        interval = int(input("更新间隔: ").strip() or 60)
    except ValueError:
        interval = 60

    # 创建并启动监控器
    monitor = RealTimeMonitor(symbols, interval)

    try:
        # 在单独线程中运行监控
        monitor_thread = threading.Thread(target=monitor.start_monitoring)
        monitor_thread.daemon = True
        monitor_thread.start()

        # 主线程处理用户命令
        print("\n💡 命令:")
        print("   'trend <SYMBOL>' - 查看股票趋势")
        print("   'add <SYMBOL>' - 添加股票到监控")
        print("   'quit' - 退出程序")

        while monitor.running:
            command = input("\n输入命令: ").strip().lower()

            if command == 'quit':
                break
            elif command.startswith('trend '):
                symbol = command.split()[1].upper()
                trend_data = monitor.get_price_trends(symbol)
                if trend_data:
                    print(f"📊 {symbol} 趋势:")
                    print(f"   方向: {trend_data['trend']}")
                    print(f"   变化: {trend_data['change']:+.2f} ({trend_data['change_percent']:+.2f}%)")
                    print(f"   平均价: ${trend_data['avg_price']:.2f}")
                else:
                    print(f"❌ {symbol} 暂无足够数据")
            elif command.startswith('add '):
                symbol = command.split()[1].upper()
                if symbol not in monitor.symbols:
                    monitor.symbols.append(symbol)
                    print(f"✅ 已添加 {symbol} 到监控列表")
                else:
                    print(f"⚠️ {symbol} 已在监控列表中")
            else:
                print("❌ 未知命令")

    except KeyboardInterrupt:
        pass
    finally:
        monitor.stop_monitoring()
        print("\n👋 程序已退出")


if __name__ == "__main__":
    main()
